from django_redis import get_redis_connection
from rest_framework import serializers

from goods.models import SKU

from drf_haystack.serializers import HaystackSerializer

from goods.search_indexes import SKUIndex


class CartSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):

        #判断商品是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        #判断库存
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('商品库存不足')

        return attrs


class SKUSerializer(serializers.ModelSerializer):

    count = serializers.IntegerField(read_only=True)
    selected = serializers.BooleanField(read_only=True)

    class Meta:
        model = SKU
        fields = '__all__'


class CartDeleteSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):

        #判断商品是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')


        return attrs


class CartSelectedSerializers(serializers.Serializer):
    selected = serializers.BooleanField()

